package com.xthh.sql_inkcute;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.os.Environment;
import android.util.Log;

import java.io.File;


/**
 * 数据库帮助类，用于创建和管理数据库
 * */
public class XTSQLiteOpenHelper_DeviceManager extends android.database.sqlite.SQLiteOpenHelper {

    public static final String DB_NAME_INKCUTE = "InkCute.db";
    private static final String TAG = "XTSQLiteOpenHelper_DeviceManager";

    /**
     * 构造方法的四个参数
     * 1.上下文
     * 2.数据库的名称
     * 3.游标工程
     * 4.数据库的版本，从1开始
     * */
    public XTSQLiteOpenHelper_DeviceManager(Context context, String name,
                                            CursorFactory factory, int version) {
        super(context, DB_NAME_INKCUTE, null, 2);
    }

    public XTSQLiteOpenHelper_DeviceManager(Context context, Application application) {
        super(new CustomPathDatabaseContext(context, getDirPath(application)), DB_NAME_INKCUTE, null, 2);
    }

    /**
     * 获取db文件在sd卡的路径
     * @return
     */
    private static String getDirPath(Application application){
        String packageName = application.getPackageName();
        packageName = packageName.replaceAll("\\.", "_");
        String rootDataDir = Environment.getExternalStorageDirectory().getPath();
        rootDataDir = rootDataDir + File.separator + "." + packageName;
        return rootDataDir;
    }

    /**
     * 数据库第一次创建的时，回调此方法
     * 初始化一些表
     * */
    @Override
    public void onCreate(SQLiteDatabase db) {


    }


    /**
     * 数据库版本号更新时回调此方法
     * 更新数据库的内容(删除表，修改表，添加表)
     * */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if(oldVersion == 1 && newVersion == 2){ //在person表中添加余额列balance
            Log.i(TAG, "数据库更新了");

            //在person表添加一列
            //String sql = String.format("alter table %s add balance integer;", DATA.SQL_SHEET_NAME_RELEASE_RECORD);
            //db.execSQL(sql);
        }
    }
}